<template>
   <div class="container">
    <el-card class="login-box">
      <el-form :model="user" :rules="rules">
        <el-form-item label="账号" prop="username">
            <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" type="password" v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" class="login-btn" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
   </el-card>
   </div>
</template>

<script lang='ts' setup>
import {reactive} from 'vue'
import {LoginType} from '../types/users'
import {FormRules,ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import api from '../api'
const router=useRouter()
//定义组件中的状态
let user=reactive<LoginType>({
  username:'',
  password:''
})
//定义表单验证规则
const rules=reactive<FormRules>({
  username:[
    {required:true,message:'请输入用户名',trigger:'blur'},
    {min:3,max:12,message:'用户名介于3-12位之间',trigger:'blur'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
  ]
})

//登录的逻辑方法
const login=async()=>{
  const result=await api.users.login(user)
  if(result.data.code){
    ElMessage.success(result.data.message)
    localStorage.setItem('token',result.data.token)
    router.replace('/')
  }else{
    ElMessage.error('用户名或密码有误')
  }  
}

</script>
<style lang='scss' scoped>
.container{
  display: flex;
  justify-content: center;
  margin-top: 100px;
  .login-box{
    display: flex;
    width: 500px;
    height: 200px;
    align-items: center;
    justify-content: center;
  .login-btn{
    width: 450px;
  }
 }
}

</style>